import axios from 'axios'
import {Message} from 'element-ui'
import {getToken, removeToken} from '@/utils/auth'
import {baseUrl} from '@/settings'
// 全局loading
import {Loading} from 'element-ui';

import router from "@/router";

let loadingCount = 0;
let loading;
const startLoading = () => {
  loading = Loading.service({
    lock: true,
    text: '加载中……',
    background: 'rgba(0, 0, 0, 0.7)'
  });
};
const endLoading = () => {
  loading.close();
};
const showLoading = () => {
  if (loadingCount === 0) {
    startLoading();
  }
  loadingCount += 1;
};
const hideLoading = () => {
  if (loadingCount <= 0) {
    return;
  }
  loadingCount -= 1;
  if (loadingCount === 0) {
    endLoading();
  }
};

function getBaseUrl() {
  if (process.env.NODE_ENV === 'development') {
    return baseUrl  //公用
  } else {
    // 正式环境
    return baseUrl
  }
}

// 创建一个实例
const service = axios.create({
  baseURL: getBaseUrl(), // url = base url + request url
  withCredentials: true, // 跨域请求时发送cookies
  timeout: 10000 // request timeout
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    //开启全局loading
    showLoading();
    return config
  },
  error => {
    // 处理请求错误
    console.log(error) // 用于调试
    return Promise.reject(error)
  }
);


// 响应拦截器
service.interceptors.response.use(
  response => {
    hideLoading();
    const res = response.data;
    // 如果自定义代码不是200，则判断为错误。
    if (res.code !== 200) {
      //登录过期
      if (res.code === 100) {
        Message.error('登录失效');
        setTimeout(() => {
          router.push('/');
        }, 1000)
      } else {
        Message.error(res.msg);
      }
    }
    return res;
  },
  error => {
    hideLoading();
    Message({
      message: '请求超时，请重试',
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error)
  }
)

export default service
